//
//  SABusinessInformationVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/8/18.
//

#import "SABusinessInformationVC.h"
#import "SAPayRegisterDetailAPI.h"
#import "SAPayRegisterDetailModel.h"
#import "SAPersonInfoVC.h"
#import "SABaseInfoVC.h"
#import "SAAccountInfoVC.h"
#import "UILabel+NSMutableAttributedString.h"
#import "SAPayInstructionsVC.h"
//#import "SAOCRViewController.h"
#import "SALivingBodyCheckAPI.h"
#import "SAPayRegisterSubmitAuditAPI.h"
#import "QRCodePermissions.h"
#import "SAPayAuthorizationVC.h"
#import "SAPayCommonLivingBodyCheckV2API.h"
#import <HSFaceDetector/LiveDetectController.h>
#import "SALivingBodyCheckModel.h"
#import "SAConsultationWechatVC.h"

@interface SABusinessInformationVC ()<HTTPAPIDelegate, LiveDetectControllerDelegate>

@property (nonatomic, strong) SAPayRegisterDetailAPI *payRegisterDetailAPI;

@property (nonatomic, strong) UILabel *personLab;
@property (nonatomic, strong) UILabel *baseInfoLab;
@property (nonatomic, strong) UILabel *accountInfoLab;
@property (nonatomic, strong) SAPayRegisterDetailModel *model;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UILabel *stateLab;
@property (nonatomic, strong) UIImageView *greenImageV;
@property (nonatomic, strong) SALivingBodyCheckAPI *livingBodyCheckAPI;
@property (nonatomic, strong) SAPayCommonLivingBodyCheckV2API *payCommonLivingBodyCheckV2API;
@property (nonatomic, strong) SAPayRegisterSubmitAuditAPI *payRegisterSubmitAuditAPI;
@property (nonatomic, strong) UIButton *submitBtn;
@property (nonatomic, strong) UIImageView *clockImageV;
@property (nonatomic, strong) UIButton *authorizationBtn;
@property (nonatomic, strong) UILabel *tapLab;
@property (nonatomic, strong) UIButton *tapBtn;

@property (nonatomic, strong) UILabel *merchantNameLab;
@property (nonatomic, strong) UILabel *merchantShortNameLab;

@end

@implementation SABusinessInformationVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.payRegisterDetailAPI sendRequestToServerWithActivityViewAndMask:POST];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.payRegisterDetailAPI == api) {
        [self.bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.stateLab.mas_bottom);
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(kScaleNum(500));
        }];
        self.greenImageV.hidden = NO;
        self.stateLab.textColor = kBlackColor;
        self.clockImageV.image = [UIImage imageNamed:@"pay_clock"];
        self.model = [SAPayRegisterDetailModel mj_objectWithKeyValues:data[@"data"]];
        if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"0"]) {
            self.stateLab.text = @"审核中...";
        }else if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"1"]) {
            self.stateLab.text = @"审核成功";
        }else if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"2"]) {
            self.stateLab.text = [NSString stringWithFormat:@"审核失败:%@",self.model.merchantDetailVO.auditMsg];
            self.stateLab.textColor = kRedColor;
            self.clockImageV.image = [UIImage imageNamed:@"pay_clock2"];
        }else {
            self.greenImageV.hidden = YES;
            [self.bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(kScaleNum(StatusHeight + 6));;
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(kScaleNum(500));
            }];
        }
        if ([self.model.merchantDetailVO.legalInfoStatus isEqualToString:@"1"]) {
            self.personLab.text = @"已完善";
            self.personLab.textColor = kBlackColor;
        }else {
            self.personLab.text = @"未完善";
            self.personLab.textColor = kLightgGrayColor;
        }
        
        if ([self.model.merchantDetailVO.baseInfoStatus isEqualToString:@"1"]) {
            self.baseInfoLab.text = @"已完善";
            self.baseInfoLab.textColor = kBlackColor;
        }else {
            self.baseInfoLab.text = @"未完善";
            self.baseInfoLab.textColor = kLightgGrayColor;
        }
        
        if ([self.model.merchantDetailVO.accountInfoStatus isEqualToString:@"1"]) {
            self.accountInfoLab.text = @"已完善";
            self.accountInfoLab.textColor = kBlackColor;
        }else {
            self.accountInfoLab.text = @"未完善";
            self.accountInfoLab.textColor = kLightgGrayColor;
        }
        
        self.submitBtn.hidden = NO;
        self.tapLab.hidden = NO;
        self.tapBtn.hidden = NO;
        self.authorizationBtn.hidden = YES;
        
        if (self.model.merchantBaseInfoVO.merchantShortName.length > 0) {
            self.merchantShortNameLab.text = self.model.merchantBaseInfoVO.merchantShortName;
        }
        if (self.model.merchantBaseInfoVO.merchantName.length > 0) {
            self.merchantNameLab.text = self.model.merchantBaseInfoVO.merchantName;
        }
        
        if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"0"]) {
            self.submitBtn.userInteractionEnabled = NO;
            [self.submitBtn setBackgroundImage:[UIImage imageNamed:@"button_gray_bg"] forState:UIControlStateNormal];
        }else if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"1"]) {
            self.submitBtn.hidden = YES;
            self.tapLab.hidden = YES;
            self.tapBtn.hidden = YES;
            self.authorizationBtn.hidden = NO;
        }else {
            if ([self.model.merchantDetailVO.legalInfoStatus isEqualToString:@"1"] && [self.model.merchantDetailVO.baseInfoStatus isEqualToString:@"1"] && [self.model.merchantDetailVO.accountInfoStatus isEqualToString:@"1"]) {
                self.submitBtn.userInteractionEnabled = YES;
                [self.submitBtn setBackgroundImage:[UIImage imageNamed:@"button_blue_bg"] forState:UIControlStateNormal];
            }else {
                self.submitBtn.userInteractionEnabled = NO;
                [self.submitBtn setBackgroundImage:[UIImage imageNamed:@"button_gray_bg"] forState:UIControlStateNormal];
            }
        }
    }else if (self.livingBodyCheckAPI == api) {
        NSString *score = data[@"data"][@"data"][@"score"];
        NSString *msg = data[@"data"][@"data"][@"msg"];
        if (msg.length == 0) {
            msg = @"人脸识别未通过";
        }
        if ([score floatValue] > 0.45) {
            [self.payRegisterSubmitAuditAPI sendRequestToServerWithActivityViewAndMask:POST];
        }else {
            [Prompt popPromptViewWithMsg:msg duration:3];
        }
    }else if (self.payRegisterSubmitAuditAPI == api) {
        [self.payRegisterDetailAPI sendRequestToServerWithActivityViewAndMask:POST];
    }else if (self.payCommonLivingBodyCheckV2API == api) {
        
        SALivingBodyCheckModel *model = [SALivingBodyCheckModel mj_objectWithKeyValues:data[@"data"]];
        if (model.pass == YES) {
            [self.payRegisterSubmitAuditAPI sendRequestToServerWithActivityViewAndMask:POST];
        }else {
            [Prompt popPromptViewWithMsg:model.msg duration:3];
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.payCommonLivingBodyCheckV2API == api) {
        [Prompt popPromptViewWithMsg:@"人脸识别未通过" duration:3];
    }
}

#pragma mark LiveDetectControllerDelegate
- (void)onFailed:(int)code withMessage:(NSString *)message{
    [Prompt popPromptViewWithMsg:@"人脸识别未通过" duration:3];
}

- (void)onFinishWithSign:(NSString *)imageSign{

    self.payCommonLivingBodyCheckV2API.idCardNo = self.model.merchantLegalPersonVO.idCardNo;
    self.payCommonLivingBodyCheckV2API.name = self.model.merchantLegalPersonVO.legalName;
    self.payCommonLivingBodyCheckV2API.packageName = @"fuyun.saasRetail";
    self.payCommonLivingBodyCheckV2API.signData = imageSign;
    
    [self.payCommonLivingBodyCheckV2API sendRequestToServerWithActivityViewAndMask:POST];
}

#pragma mark - LivenessDetectDelegate
- (void)onLiveDetectCompletion:(NSDictionary *)result{
    NSString *code = [result objectForKey:@"code"];
    if ([code isEqualToString:@"0"]) {
        NSString *passFace = [result objectForKey:@"passFace"];
        
        self.livingBodyCheckAPI.idCardNo = self.model.merchantLegalPersonVO.idCardNo;
        self.livingBodyCheckAPI.name = self.model.merchantLegalPersonVO.legalName;
        self.livingBodyCheckAPI.image = passFace;
        [self.livingBodyCheckAPI sendRequestToServerWithActivityViewAndMask:POST];
    }else{
        NSString *msg = [result objectForKey:@"msg"];
        if (msg.length == 0) {
            msg = @"人脸识别未通过";
        }
        [Prompt popPromptViewWithMsg:msg duration:3];
    }
}

#pragma mark - event
-(void)clickRightBtn:(UIButton *)sender {
    if (sender.tag == 1) {
        SAPersonInfoVC *pushVC = [[SAPersonInfoVC alloc] initWithModel:self.model];
        [self.navigationController pushViewController:pushVC animated:YES];
    }else if (sender.tag == 2) {
        SABaseInfoVC *pushVC = [[SABaseInfoVC alloc] initWithModel:self.model];
        [self.navigationController pushViewController:pushVC animated:YES];
    }else {
        SAAccountInfoVC *pushVC = [[SAAccountInfoVC alloc] initWithModel:self.model];
        [self.navigationController pushViewController:pushVC animated:YES];
    }
}

-(void)clickedSubmitBtn {
    if (![QRCodePermissions allowCamera]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请开启摄像头权限" message:@"请在\"设置 - 隐私 - 相机\"选项中，允许访问您的相机" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action];
        [alert addAction:action2];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
        return;
    }
//    [self.navigationController pushViewController:[SAOCRViewController new] animated:YES];
    //    NSDictionary *param = @{@"actions":@"1279", @"actionsNum":@"3"};
    //    [[Liveness shareInstance] startProcess:self withParam:param withDelegate:self];
    
    NSInteger liveMode = [[NSUserDefaults standardUserDefaults]integerForKey:@"live_mode"];
    
    LiveDetectController *liveVc = [[LiveDetectController alloc]init];
    if (liveMode == 0) {
        NSMutableArray *temp = [self randomArray:@[@2, @3, @4, @5] withRandomNum:2];
        [temp addObject:@1];
        liveVc.actionList = [temp copy];
    }else{
        liveVc.actionList = @[@1];
    }
    liveVc.minFaceSize = [[[NSUserDefaults standardUserDefaults]objectForKey:@"min_face_size"] intValue];
    liveVc.maxFaceSize = [[[NSUserDefaults standardUserDefaults]objectForKey:@"max_face_size"] intValue];
    liveVc.actionTimeout = [[[NSUserDefaults standardUserDefaults]objectForKey:@"time_out_second"] intValue];
    liveVc.delegate = self;
    liveVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:liveVc animated:YES completion:nil];
    
}

//随机数组
- (NSMutableArray *)randomArray:(NSArray *)array withRandomNum:(NSInteger)num {
    
    NSMutableArray *startArray = [[NSMutableArray alloc] initWithArray:array];
    //随机数产生结果
    NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:0];
    //随机数个数
    for (int i = 0; i < num; i++) {
        int t = arc4random() % startArray.count;
        resultArray[i] = startArray[t];
        startArray[t] = [startArray lastObject]; //为更好的乱序，故交换下位置
        [startArray removeLastObject];
    }
    return resultArray;
}

-(void)clickedTapBtn {
    
    SAConsultationWechatVC *pushVC = [[SAConsultationWechatVC alloc] init];
    [self.navigationController pushViewController:pushVC animated:YES];
    
//    SAPayInstructionsVC *pushVC = [[SAPayInstructionsVC alloc] init];
//    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)clickedAuthorizationBtn {
    SAPayAuthorizationVC *pushVC = [[SAPayAuthorizationVC alloc] init];
    [self.navigationController pushViewController:pushVC animated:YES];
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"商户信息"];
    self.view.backgroundColor = kLineColor;
    
    UIImageView *greenImageV = [[UIImageView alloc] init];
    greenImageV.image = [UIImage imageNamed:@"pay_lightGreen"];
    [self.view addSubview:greenImageV];
    self.greenImageV = greenImageV;
    
    UIImageView *clockImageV = [[UIImageView alloc] initWithFrame:SARectMake(26, 10, 20, 20)];
    clockImageV.image = [UIImage imageNamed:@"pay_clock"];
    clockImageV.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:clockImageV];
    self.clockImageV = clockImageV;
    
    UILabel *stateLab = [[UILabel alloc] init];
    stateLab.font = kFont(15);
    stateLab.textColor = kBlackColor;
    stateLab.textAlignment = NSTextAlignmentLeft;
    stateLab.numberOfLines = 0;
    [self.view addSubview:stateLab];
    self.stateLab = stateLab;
    
    [stateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kScaleNum(56));
        make.top.mas_equalTo(kScaleNum(StatusHeight));
        make.right.mas_equalTo(0);
        make.height.mas_greaterThanOrEqualTo(kScaleNum(40));
    }];
    
    [clockImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kScaleNum(26));
        make.top.bottom.equalTo(stateLab);
        make.width.mas_equalTo(kScaleNum(20));
    }];
    
    [greenImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.bottom.equalTo(stateLab);
    }];
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = kLineColor;
    [self.view addSubview:bgView];
    self.bgView = bgView;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(stateLab.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(500));
    }];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, 163)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:whiteView];
    
    NSArray *arr = @[@"店铺名称",@"商户名称", @"商户简称", @"账户"];
    for (int i = 0; i < arr.count; i++) {
        UILabel *lab1 = [[UILabel alloc] initWithFrame:SARectMake(26, i * 41, 100, 40)];
        lab1.text = arr[i];
        lab1.font = kFont(15);
        lab1.textColor = kBlackColor;
        lab1.textAlignment = NSTextAlignmentLeft;
        [whiteView addSubview:lab1];
        
        UILabel *lab2 = [[UILabel alloc] initWithFrame:SARectMake(157, i * 41, 200, 40)];
        lab2.font = kFont(15);
        lab2.textColor = kBlackColor;
        lab2.textAlignment = NSTextAlignmentLeft;
        [whiteView addSubview:lab2];
        
        if (i == 0) {
            lab2.text = [SAValueManger shareInStance].userInfo.storeName;
        }else if (i == 1) {
            lab2.text = [SAValueManger shareInStance].userInfo.empName;
            self.merchantNameLab = lab2;
        }else if (i == 2) {
            self.merchantShortNameLab = lab2;
        }else if (i == 3) {
            lab2.text = [SAValueManger shareInStance].userInfo.mobile;
        }
        
        if (i != 3) {
            UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, i * 41 + 40, kBaseScreenWidth, 1)];
            line.backgroundColor = kLineColor;
            [whiteView addSubview:line];
        }
    }
    
    UIView *whiteView2 = [[UIView alloc] initWithFrame:SARectMake(0, 173, kBaseScreenWidth, 122)];
    whiteView2.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:whiteView2];
    
    NSArray *arr2 = @[@"身份资料", @"经营信息", @"收款卡信息"];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *lab1 = [[UILabel alloc] initWithFrame:SARectMake(26, i * 41, 100, 40)];
        lab1.text = arr2[i];
        lab1.font = kFont(15);
        lab1.textColor = kBlackColor;
        lab1.textAlignment = NSTextAlignmentLeft;
        [whiteView2 addSubview:lab1];
        
        UILabel *lab2 = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 130, i * 41, 100, 40)];
        lab2.text = @"未完善";
        lab2.font = kFont(15);
        lab2.textColor = kLightgGrayColor;
        lab2.textAlignment = NSTextAlignmentRight;
        [whiteView2 addSubview:lab2];
        
        if (i == 0) {
            self.personLab = lab2;
        }else if (i == 1) {
            self.baseInfoLab = lab2;
        }else if (i == 2) {
            self.accountInfoLab = lab2;
        }
        
        if (i != 2) {
            UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, i * 41 + 40, kBaseScreenWidth, 1)];
            line.backgroundColor = kLineColor;
            [whiteView2 addSubview:line];
        }
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setImage:[UIImage imageNamed:@"pay_arrow_right"] forState:UIControlStateNormal];
        rightBtn.frame = SARectMake(0, i * 41, kBaseScreenWidth, 40);
        rightBtn.titleLabel.font = kFont(15);
        [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, kScaleNum(13));
        rightBtn.tag = 1 + i;
        [rightBtn addTarget:self action:@selector(clickRightBtn:) forControlEvents:UIControlEventTouchUpInside];
        [whiteView2 addSubview:rightBtn];
    }
    
    UIButton *authorizationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    authorizationBtn.frame = CGRectMake(0, kScaleNum(299), kScreenWidth, kScaleNum(35));
    [authorizationBtn setTitle:@"资料审核通过了,去授权支付>>" forState:UIControlStateNormal];
    [authorizationBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    authorizationBtn.titleLabel.font = kFont(16);
    [authorizationBtn addTarget:self action:@selector(clickedAuthorizationBtn) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:authorizationBtn];
    authorizationBtn.hidden = YES;
    self.authorizationBtn = authorizationBtn;
    
    UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [submitBtn setBackgroundImage:[UIImage imageNamed:@"button_gray_bg"] forState:UIControlStateNormal];
    submitBtn.frame = CGRectMake(kScaleNum(70), kScaleNum(335), kScaleNum(235), kScaleNum(35));
    [submitBtn setTitle:@"提交审核" forState:UIControlStateNormal];
    submitBtn.titleLabel.font = kFont(16);
    [submitBtn addTarget:self action:@selector(clickedSubmitBtn) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:submitBtn];
    self.submitBtn = submitBtn;
    submitBtn.userInteractionEnabled = NO;
    
    UILabel *tapLab = [[UILabel alloc] initWithFrame:SARectMake(0, 381, kBaseScreenWidth, 15)];
    tapLab.font = kFont(13);
    tapLab.text = @"注册遇到问题？添加客服咨询>";
    tapLab.textColor = kBuleColor;
    tapLab.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:tapLab];
    self.tapLab = tapLab;
    
    UIButton *tapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tapBtn.frame = SARectMake(0, 376, kBaseScreenWidth, 25);
    [tapBtn addTarget:self action:@selector(clickedTapBtn) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:tapBtn];
    self.tapBtn = tapBtn;
    
    if ([[SAValueManger shareInStance].userInfo.auditStatus isEqualToString:@"3"]) {
        self.greenImageV.hidden = YES;
        [bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kScaleNum(StatusHeight + 6));;
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(kScaleNum(500));
        }];
    }
}

-(SAPayRegisterDetailAPI *)payRegisterDetailAPI {
    if (!_payRegisterDetailAPI) {
        _payRegisterDetailAPI = [SAPayRegisterDetailAPI apiWithDelegate:self];
    }
    return _payRegisterDetailAPI;
}

-(SALivingBodyCheckAPI *)livingBodyCheckAPI {
    if (!_livingBodyCheckAPI) {
        _livingBodyCheckAPI = [SALivingBodyCheckAPI apiWithDelegate:self];
    }
    return _livingBodyCheckAPI;
}

-(SAPayRegisterSubmitAuditAPI *)payRegisterSubmitAuditAPI {
    if (!_payRegisterSubmitAuditAPI) {
        _payRegisterSubmitAuditAPI = [SAPayRegisterSubmitAuditAPI apiWithDelegate:self];
    }
    return _payRegisterSubmitAuditAPI;
}

-(SAPayCommonLivingBodyCheckV2API *)payCommonLivingBodyCheckV2API {
    if (!_payCommonLivingBodyCheckV2API) {
        _payCommonLivingBodyCheckV2API = [SAPayCommonLivingBodyCheckV2API apiWithDelegate:self];
    }
    return _payCommonLivingBodyCheckV2API;
}

@end
